<?php
/*
 * 联系人控制器
 */
class Contacter extends CI_Controller {
	function __construct() {
		parent::__construct ();
		$this->load->helper ( 'url' );
		$this->load->library ( 'pagination' );
	}

	public function index($offset = '',$error_info = '') {
		$user_name=$this->session->userdata('username');
		if($user_name){
			$this->load->model ( 'contacter_model', 'contacter' );
			$limit = 10;
			$total = $this->contacter->count_nums ();
			$data['total']=$total;
			$data['offset']=$offset;
			$data ['contacter'] = $this->contacter->list_contacters ( $limit, $offset );

			$current_total=count($data ['contacter']);
			$data['current_total']=$offset+$current_total;

			$config ['base_url'] = base_url () . 'index.php/contacter/index/';
			$config ['total_rows'] = $total;
			$config ['per_page'] = $limit;
			$config ['num_links'] = 4;
			$config ['first_link'] = '首页';
			$config ['last_link'] = '尾页';
			$this->pagination->initialize ( $config );
			$data ['pag_links'] = $this->pagination->create_links ();

			$data ['page_title'] = '联系人 — 昊美科技CRM系统';
			$data ['class2'] = 'cur';
			$data ['error_info'] = $error_info;
			$data ['parent_customers'] = $this->check_parent_customers();
			$this->load->view ( 'contacter_list', $data );
		}else{
			$this->load->view ( 'login');
		}
	}

	public function find_error_drop($error_info){ /*添加,编辑出现条件不满足时调用*/
		$this->index('',$error_info);
	}

	/*
	 * 查看某条记录
	*/
	public function find($id = '') {
		$data = $this->check_find($id);
		$this->load->view ( 'contacter_view',$data);
	}
	
	public function console_find_contacter(){
		$data = $this->check_find($id);
		$this->load->view ( 'console_contacter_view',$data);
	}
	
	public function check_find($id = ''){
		$this->db->select('customer.customer_name,contacter.*');
		$this->db->from('customer');
		$this->db->join('contacter', 'customer.id = contacter.customer_id');
		$this->db->where('contacter.id', $id);
		$query = $this->db->get();
		$data['find_contacter'] = $query->row();
		/*查询历任单位*/
		$q = $this->db->get_where('old_units',array('contracter_id'=>$id));
		$data['old_units'] = $q->result();
		return $data;
	}
	
	/*
	 * 客户名查询记录
	*/
	public function check($name = ''){
		$this->db->select('*')->from('customer')->join('contacter', 'customer.id = contacter.customer_id')->like('contacter.name', urldecode($name))->order_by('contacter.last_contact_time', "desc");
		$query = $this->db->get();
		$data['contacter'] = $query->result();
		$data ['pag_links'] = '';
		$data ['page_title'] = '联系人 — 昊美科技CRM系统';
		$data ['class2'] = 'cur';
		$this->load->view ( 'contacter_list', $data );
	}

	/*
	 * 查看某条编辑记录
	*/
	public function edit($id = '') {
		$this->db->select('customer.id as customer_id,customer.customer_name as customer_name,contacter.*');
		$this->db->from('customer');
		$this->db->join('contacter', 'customer.id = contacter.customer_id');
		$this->db->where('contacter.id', $id);
		$query = $this->db->get();
		$data['update_contacter'] = $query->row();

		/*查询历任单位*/
		$q = $this->db->get_where('old_units',array('contracter_id'=>$id));
		$data['old_units'] = $q->result();

		$this->load->view ( 'contacter_edit',$data);
	}

	/*
	 * 编辑某条记录
	*/
	public function update() {
		$data_array = $_POST; /*接受参数数组*/
		if(!trim($data_array['customer_name']) || !trim($data_array['name']) || !trim($data_array['appellation']) || !trim($data_array['department']) || !trim($data_array['post'])){
// 			redirect ( 'contacter/index/' );
			$this->find_error_drop('修改失败,数据不允许为空');
		}else{
			$id = $data_array['id'];
			$customer_id='';
			if($data_array['customer_name'] != $data_array['hidden_name']){ /*修改了对应客户*/
				$this->db->select('id')->from('customer')->where('customer_name', $data_array['customer_name']);
				$rows = $this->db->get()->result();
				$customer_id=$rows[0]->id;
				if(!$customer_id){ //如果输入的对应客户不存在
// 					redirect ( 'contacter/index/' );
					$this->find_error_drop('修改失败,对应客户不存在');
					return;
				}
			}else{
				/*获取客户编号*/
				$customer_id=$data_array['customerid'];
			}
			unset($data_array['customer_name']);
			unset($data_array['hidden_name']);
			unset($data_array['customerid']);
			$data_array['customer_id']=$customer_id;

			unset($data_array['id']);
			$this->db->where('id', $id);
			$this->db->update('contacter', $data_array);
			redirect ( 'contacter/index/' );
		}
	}

	/*
	 * 删除记录
	*/
	public function delete($id = '') {
		$this->db->delete ( 'contacter', array ('id' => $id ) );
		redirect ( 'contacter/index/' );
	}

	/*
	 * 增加联系人
	 */
	public function show_contacter_add($customer_name = ''){
		$data['customer_name'] = urldecode($customer_name);
		$this->load->view ( 'contacter_add',$data);
	}

	public function insert() {
		$data_array = $_POST;
		if(!trim($data_array['customer_name']) || !trim($data_array['name']) || !trim($data_array['appellation']) || !trim($data_array['department']) || !trim($data_array['post'])){
// 			redirect ( 'contacter/index/');
			$this->find_error_drop('添加失败,数据不允许为空');
		}else{
			$this->db->select('id')->from('customer')->where('customer_name', $data_array['customer_name']); /*通过客户名查询客户编号*/
			$query = $this->db->get();
			foreach ($query->result() as $rows){
				$customer_id=$rows->id;
			}
			if(!$customer_id){ //如果输入客户不存在
// 				redirect ( 'contacter/index/' );
				$this->find_error_drop('添加失败,对应客户不存在');
			}else{
				unset($data_array['customer_name']);
				$data_array['customer_id']=$customer_id;

				date_default_timezone_set('PRC');
				$now_time=date('Y-m-d H:i:s', strtotime('now'));
				$data_array['create_time']=$now_time;

				$this->db->insert('contacter', $data_array);
				$row=$this->db->affected_rows();
				if($row > 0){
					redirect ( 'contacter/index/' );
				}else{
				}
			}
		}
	}

	/*动态搜索*/
	function autosearch($name = ''){
			$user_role = $this->session->userdata('role');
			$user_id = $this->session->userdata('id');
			$contacter_names =array();
			$contacter_names['q'] = urldecode($name);
			$contacter_names['p'] = true;
			$contacter_names['s'] = array();
			//echo urldecode($name);
			if($user_role != '商务助理'){
				if(!$name){
					$this->db->select('customer_name')->where('user_id',$user_id)->from('customer');
				}else{
					$this->db->select('id,customer_name')->like('customer_name', urldecode($name))->from('customer');
				}
				$query = $this->db->get();
			}else{
				if($name){
					if(!$name){
						$this->db->select('customer_name')->from('customer');
					}else{
						$this->db->select('id,customer_name')->like('customer_name', urldecode($name))->from('customer');
					}
					$query = $this->db->get();
				}
			}
			foreach($query->result() as $row){
				$contacter_names['s'][] = $row->customer_name;
			}
			//echo '<pre>';
			//print_r($contacter_names['s']);

			$json_string = json_encode($contacter_names);
			echo "window.baidu.sug($json_string)";
	}

	/*添加历任单位*/
	public function add_old_units(){
		$data_array = $_POST;
		$data=array('appellation' => '','type' => '','post'=>'','department'=>'');
		$this->db->where('id', $data_array['id']);
		$query = $this->db->update('contacter', $data);
		if($query == 1){
			$data_array['contracter_id'] = $data_array['id'];
			unset($data_array['id']);
			$now_time=date('Y-m-d H:i:s', strtotime('now'));
			$data_array['create_time']=$now_time;
			$query =$this->db->insert('old_units', $data_array);
			if($query == 1){
				/*查询新添加历任单位编号*/
				$this->db->select('id')->like('create_time', $now_time)->from('old_units');
				$q = $this->db->get();
				$row = $q->row();
				echo $row->id;;
			}else{
				echo 0;
			}
		}else{
		    echo 0;
		}
	}

	/*删除历任单位*/
	public function delete_old_units(){
		$data_array = $_POST;
		$q = $this->db->delete('old_units', array('id' => $data_array['id']));
		if($q == 1){
			echo 1;
		}else{
			echo 0;
		}
	}

	/*查询联系人对应的父级客户*/
	public function check_parent_customers(){
		$role = $this->session->userdata('role');
		$user_id =$this->session->userdata('id');
		if($role == '市场'){
			$condition = ' contacter.customer_id in (select id from customer where user_id = '.$user_id.') ';
		}else{
//			$condition = ' customer.id in (SELECT DISTINCT customer_id from contacter where customer_id <> 0) and customer.parent_id = 0';
			$condition = ' customer.parent_id = 0';
		}
		$sql = 'SELECT DISTINCT customer.id as customer_id, customer.customer_name as customer_name,
				customer.user_id as customer_user_id, customer.parent_id as parent_id
				FROM (customer) JOIN contacter ON customer.id = contacter.customer_id
				where '.$condition.' order by contacter.create_time desc ';
		$query = $this->db->query($sql);
		$customers = $query->result();
		$count = count($customers);
		$parent_id_array = array();

		for($i=0;$i<$count;$i++){
			if($customers[$i]->parent_id){
				$parent_id_array[]=$customers[$i]->parent_id;
				unset($customers[$i]);
			}
		}

		$data_unique = array_unique($parent_id_array);
		for($i=0;$i<count($data_unique);$i++){
			for($d=0;$d<$count;$d++){
				if($customers[$d]->customer_id == $data_unique[$i]){
					unset($data_unique[$i]);
				}
			}
		}
		$maxkey = 0;
		foreach($customers as $key => $value) {
			if($key >= $maxkey){
				$maxkey = $key;
			}
		}
		$o=1;
		for($a=0;$a<count($data_unique);$a++){
			$query = $this->db->query("SELECT customer.id as customer_id, customer.customer_name as customer_name ,customer.user_id as customer_user_id, customer.parent_id as parent_id FROM customer where id = $data_unique[$a]");
			foreach ($query->result() as $row){
				$customers[$maxkey+$o] = (object)array(
					'customer_id' => $row->customer_id,
					'customer_name' => $row->customer_name,
					'customer_user_id' => $row->customer_user_id,
					'parent_id' => $row->parent_id
					);
			}
			$o++;
		}
		/*获取没有直接客户的子客户的父级客户*/
		if($role == '商务助理' || $role == '经理'){
			$no_parent_customer_sql = 'select id as customer_id,customer_name,user_id as customer_user_id,parent_id
										from customer where id in (SELECT DISTINCT customer.parent_id as parent_id
										FROM (customer) JOIN contacter ON customer.id = contacter.customer_id
										where customer.parent_id not in (SELECT DISTINCT customer.id as customer_id
										FROM (customer) JOIN contacter ON customer.id = contacter.customer_id
										where customer.parent_id = 0 ) and customer.parent_id !=0)';
			$query = $this->db->query($no_parent_customer_sql);
			$no_parent_customers = $query->result();
			$result = array_merge ($customers, $no_parent_customers);
			return $result;
		}else{
			return $customers;
		}
	}

	public function get_contacer_county(){
		$data_array = $_POST;
		$parent_id = $data_array['parent_id'];
		$role = $this->session->userdata('role');
		$user_id =$this->session->userdata('id');
		$condition = '(parent_id = '.$parent_id.'  or id = '.$parent_id.')';
		if($role == '市场'){
			$condition = '(parent_id = '.$parent_id.'  or id = '.$parent_id.') and user_id = '.$user_id.'';
		}
		$sql = 'SELECT DISTINCT customer.customer_name as customer_name,customer.id as customer_id
				FROM (customer) JOIN contacter ON customer.id = contacter.customer_id
				where contacter.customer_id in (select id from customer where  '.$condition.')
				order by contacter.create_time desc ';
		$query = $this->db->query($sql);
		$county_customers = $query->result();
		$json_string = json_encode($county_customers);
		echo $json_string;
	}

	public function con_city_customers($city_id = '',$county_id = ''){
		$user_id =$this->session->userdata('id');
		$role = $this->session->userdata('role');
		$sql = 'SELECT customer.id as customer_id, customer.customer_name as customer_name,
				customer.user_id as customer_user_id, customer.parent_id as parent_id,contacter.*
				FROM (customer) JOIN contacter ON customer.id = contacter.customer_id ';
		if($county_id){ /*市级搜索*/
			$sql.=' where contacter.customer_id = '.$county_id.' order by contacter.create_time desc';
		}else{
			if($role == '商务助理' || $role == '经理'){
				$query = $this->db->query('SELECT customer_id FROM contacter where customer_id = '.$city_id.'');
			}else{
				$query = $this->db->query('SELECT customer_id FROM contacter inner join customer on customer.id = contacter.customer_id where customer_id = '.$city_id.' and customer.user_id = '.$user_id.'');
			}
			$result = $query->result_array();
			if(!count($result)){
				if($role == '商务助理' || $role == '经理'){
					$sql.=' where contacter.customer_id in (SELECT id FROM customer where parent_id = '.$city_id.') order by contacter.create_time desc';
				}else{
					$sql.=' where contacter.customer_id in (SELECT id FROM customer where parent_id = '.$city_id.' and user_id = '.$user_id.') order by contacter.create_time desc';
				}
			}else{
				if($role == '商务助理' || $role == '经理'){
					$sql.=' where contacter.customer_id in (select id from customer where parent_id= '.$city_id.' or id = '.$city_id.')  order by contacter.create_time desc';
				}else{
					$sql.=' where contacter.customer_id in (select id from customer where (parent_id= '.$city_id.' or id = '.$city_id.') and user_id = '.$user_id.')  order by contacter.create_time desc';
				}
			}
		}
		$query = $this->db->query($sql);
		$contacters = $query->result();

		$data ['contacter'] = $contacters;
		$data ['page_title'] = '联系人 — 昊美科技CRM系统';
		$data ['class2'] = 'cur';
		$data ['parent_customers'] = $this->check_parent_customers();

		$data ['con_city_id'] = $city_id;
		$data ['con_county_id'] = $county_id;

		$condition = '(parent_id = '.$city_id.'  or id = '.$city_id.')';
		if($role == '市场'){
			$condition = '(parent_id = '.$city_id.'  or id = '.$city_id.') and user_id = '.$user_id.'';
		}

		$sql = 'SELECT DISTINCT customer.customer_name as customer_name,customer.id as customer_id
				FROM (customer) JOIN contacter ON customer.id = contacter.customer_id
				where contacter.customer_id in (select id from customer where  '.$condition.')
				order by contacter.create_time desc ';
		$query = $this->db->query($sql);
		$data ['county_customers'] = $query->result();

		$con_count = count($data ['contacter']);
		$data ['check_pag_links'] = '1';
		$data ['total'] = $con_count;
		$data ['current_total'] = $con_count;
		$this->load->view ( 'contacter_list', $data );
	}

}
